/**
 * All Rights Reserved , Copyright (C) 2023 , 青岛鼎信通讯股份有限公司
 * <p>
 * CjCompareJobResultController 文件对比结果
 * <p>
 * 修改纪录 2023-02-22 版本：1.0 zhanglongfei 创建。
 *
 * @version 版本：1.0
 * @author 作者：zhanglongfei 创建日期：2023-02-22
 */

package com.topscomm.mis.cbb.file.compare.cj.controller;

import com.alibaba.fastjson.JSONObject;
import com.topscomm.mis.cbb.file.compare.cj.controller.auto.CjCompareJobResultControllerAuto;
import com.topscomm.mis.cbb.file.compare.cj.pojo.dto.CompareItemsDto;
import com.topscomm.mis.cbb.file.compare.cj.pojo.dto.CompareParagraphStyleDto;
import com.topscomm.mis.cbb.file.compare.cj.pojo.dto.CompareTableStyleDto;
import com.topscomm.mis.cbb.file.compare.cj.pojo.dto.CompareTextStyleDto;
import com.topscomm.mis.cbb.file.compare.word.util.PoiWordUtil;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.log4j.Log4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author: zhanglongfei
 * @date: 2023-02-22
 * @description:文件对比结果Controller
 * @modify:
 */
@Log4j
@RestController
@RequestMapping("cj/compareJobResult")
public class CjCompareJobResultController extends CjCompareJobResultControllerAuto implements
    ICjCompareJobResultController {

    /**
     * @param paraMap
     * @return
     * @author: zhanglongfei
     * @date: 2023-02-22
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_sourceapp")) {
            String value = paraMap.get("qry_sourceapp").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and sourceapp = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_sourcetype")) {
            String value = paraMap.get("qry_sourcetype").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and sourcetype = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_sourceid")) {
            String value = paraMap.get("qry_sourceid").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and sourceid = '{0}' ", value);
            }
        }
        if (paraMap.containsKey("qry_difftype")) {
            String value = paraMap.get("qry_difftype").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and difftype = '{0}' ", value);
            }
        }
        return sql.toString();
    }

    /**
     * @param files:
     * @param paraMap:
     * @description: 比对文件接口
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author: zhanglongfei
     * @date: 2023/2/24 11:37
     * @modify:
     */
    @PostMapping(value = "/compareWords")
    public ResponseResult<Object> compareWords(@RequestParam("files") MultipartFile[] files,
        @RequestParam(required = false) Map<String, Object> paraMap) {
        File attachFile1 = null, attachFile2 = null;
        try {
            if (files == null || files.length <= 1) {
                return ResponseResult.error("找不到合法的文件");
            }
            BaseUtil.decodeSecureMap(paraMap);
            attachFile1 = multipartFileToFile(files[0]);
            attachFile2 = multipartFileToFile(files[1]);
            CompareItemsDto compareItemsDto = new CompareItemsDto();
            if (paraMap.containsKey("compareItemsDto")){
                compareItemsDto = JSONObject
                    .parseObject(ConvertUtil.convertToString(paraMap.get("compareItemsDto")),
                        CompareItemsDto.class);
            }else {
                CompareTableStyleDto compareTableStyleDto = new CompareTableStyleDto();
                CompareParagraphStyleDto compareParagraphStyleDto = new CompareParagraphStyleDto();
                CompareTextStyleDto compareTextStyleDto = new CompareTextStyleDto();
                compareItemsDto.setCompareContent(true);
                compareItemsDto.setCompareParagraphStyleDto(compareParagraphStyleDto);
                compareItemsDto.setCompareTableStyleDto(compareTableStyleDto);
                compareItemsDto.setCompareTextStyleDto(compareTextStyleDto);
            }
//            PoiWordUtil.mergeDocuments(files);
            Map<String, Object> resultMap = service
                .compareWords(attachFile1, attachFile2, paraMap, compareItemsDto);
            return ResponseResult.ok(resultMap);
        } catch (Exception e) {
            return ResponseResult.error(e.getMessage());
        } finally {
            if (attachFile1 != null) {
                attachFile1.delete();
            }
            if (attachFile2 != null) {
                attachFile2.delete();
            }
        }
    }

    /**
     * @param paraMap:
     * @description: 保存CehckList
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author: zhanglongfei
     * @date: 2023/2/27 20:08
     * @modify:
     */
    @PostMapping(value = "saveCheckList")
    public ResponseResult<Object> saveCheckList(
        @RequestBody(required = false) Map<String, Object> paraMap) {
        try {
            Map<String, Object> dataMap = (Map<String, Object>) paraMap.get("params");
            dataMap = BaseUtil.decodeSecureMap(dataMap);
            List<Map<String, Object>> checkList = (List<Map<String, Object>>) paraMap
                .get("checkList");
            service.saveCheckList(dataMap, checkList);
            return ResponseResult.ok("保存成功");
        } catch (Exception ex) {
            return ResponseResult.error(ex.getMessage());
        }
    }

    /**
     * @description: 查询差异列表
     * @author: liwanpeng
     * @date: 2023-02-28 09:02:27
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @modify:
     */
    @GetMapping(value = "queryCheckList")
    public ResponseResult<Object> queryCheckList(
        @RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            String sqlWhere = this.spellListSql(paraMap);
            List<Map<String, Object>> resultList = service.queryMapByWhere(sqlWhere);
            return ResponseResult.ok(resultList);
        } catch (Exception ex) {
            return ResponseResult.error(ex.getMessage());
        }
    }

    /**
     * description 文档合并
     * @author wxm
     * @date 2023-06-20 09:50:07
     * @param files
     * @return com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @modify
     */
    @PostMapping(value = "mergeDocuments")
    public ResponseResult<Object> mergeDocuments(@RequestParam("files") MultipartFile[] files, @RequestParam("useSection") Boolean useSection) {
        try {
            byte[] resultFileByte = PoiWordUtil.mergeDocuments(files,useSection);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("result", resultFileByte);
            return ResponseResult.ok(resultMap);
        } catch (Exception ex) {
            log.error("文档合并出错：", ex);
            return ResponseResult.error(ex.getMessage());
        }
    }


    private File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file == null || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    private void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

